//
//  KLCarDetailViewController.m
//  KunLun
//
//  Created by Mac on 2017/12/28.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLCarDetailViewController.h"
#import "KLCarDetailModel.h"
#import "NSDate+STFormatter.h"
#import "STActionSheet.h"
@interface KLCarDetailViewController ()<STActionSheetDelegate>
@property(nonatomic, strong) KLCarDetailModel                     *detailModel;
@property(nonatomic, strong) NSArray                     *dataSouce;
@end

@implementation KLCarDetailViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"货运详情";
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendDetailRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    [self addNotifacations];
   
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --subView
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
   
    
   
    CGFloat top = 10;
    for (int i =0; i < self.detailModel.pictures.count; i ++) {
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, top, UIScreenWidth - 40, 170)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.detailModel.pictures[i]]];
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [footer addSubview:imageView];
        top = imageView.bottom + 10;
        imageView.tag = 10000 + i;
        UITapGestureRecognizer * ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSelectedImageView:)];
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:ges];
    }
    footer.height = top + 10 + 49;
    
    self.tableView.tableFooterView = footer;
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(youShouldRefresh)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
}
- (void)youShouldRefresh{
    [self.tableView.mj_header beginRefreshing];
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark --subView
- (void)configTableHeader{
    self.tableView.height = UIScreenHeight - 49;
    
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 20)];
    header.backgroundColor = [UIColor whiteColor];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 10, UIScreenWidth - 2 * self.insetX, 20)
                                                     text:self.detailModel.title
                                                textColor:FlatBlack
                                                     font:14
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [header addSubview:titleLable];
    [NSString lableAutoAdjustheightWithLabel:titleLable];
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:self.detailModel.created_at.integerValue];
    STLabel * timeLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, titleLable.bottom + 5, UIScreenWidth - 2 * self.insetX, 20)
                                                    text:date.st_yyyyMMddByLineWithDate
                                               textColor:KL_secendTextColor
                                                    font:13
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentLeft];
    [header addSubview:timeLable];
    header.height = timeLable.bottom + 15;
    self.tableView.tableHeaderView = header;
}
- (void)configTableFooter{
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 20)];
    footer.backgroundColor = [UIColor whiteColor];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, 0, UIScreenWidth, 44)
                                                     text:@"货运详情:"
                                                textColor:KL_firstTextColor
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    [footer addSubview:titleLable];
    
    STLabel * desLable = [[STLabel alloc] initWithFrame:CGRectMake(self.insetX, titleLable.bottom, UIScreenWidth - 2 * self.insetX, 20)
                                                   text:self.detailModel.details
                                              textColor:KL_secendTextColor
                                                   font:14
                                            isSizetoFit:NO
                                          textAlignment:NSTextAlignmentLeft];
    [footer addSubview:desLable];
    [NSString lableAutoAdjustheightWithLabel:desLable];
    
    footer.height = desLable.bottom  +20;
    self.tableView.tableFooterView = footer;
}
- (void)configDataSouce{
    
    self.dataSouce = @[
                       [[STTableEasyModel alloc] initWithTextString:@"所需车辆" detailString:self.detailModel.vehicle],
                       [[STTableEasyModel alloc] initWithTextString:@"上货地址" detailString:self.detailModel.cargo_address],
                       [[STTableEasyModel alloc] initWithTextString:@"联系人" detailString:self.detailModel.name],
                       [[STTableEasyModel alloc] initWithTextString:@"送货目的地" detailString:self.detailModel.discargo_address],
                       [[STTableEasyModel alloc] initWithTextString:@"描述路线" detailString:self.detailModel.address_describe],
                       [[STTableEasyModel alloc] initWithTextString:@"货车数量"
                                                       detailString:self.detailModel.inventory.description],
                       ];
    [self.tableView reloadData];
}
- (void)reloadData{
    if (self.detailModel) {
        [self configTableFooter];
        [self configTableHeader];
        [self configBootomView];
        [self configDataSouce];
    }
    
}
- (void)configBootomView{
    __weak typeof(self) weakSelf =  self;
    STButton * phoneButton = [[STButton alloc] initWithFrame:CGRectMake(0, [KLUtils tabBarTop], UIScreenWidth / 2, 49)
                                                       title:@"电话"
                                                  titleColor:KL_firstTextColor
                                                   titleFont:17
                                                cornerRadius:0
                                             backgroundColor:[UIColor whiteColor]
                                             backgroundImage:nil
                                                       image:nil];
    phoneButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [phoneButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedPhoneButton];
    }];
    [self.view addSubview:phoneButton];
    
    STButton * contactButton = [[STButton alloc] initWithFrame:CGRectMake(UIScreenWidth / 2, [KLUtils tabBarTop], UIScreenWidth / 2, 49)
                                                         title:@"联系"
                                                    titleColor:FlatWhite
                                                     titleFont:17
                                                  cornerRadius:0
                                               backgroundColor:KL_BlueBackGroundColor
                                               backgroundImage:nil
                                                         image:nil];
    contactButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [contactButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedContactButton];
    }];
    [self.view addSubview:contactButton];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    STTableEasyModel * model =   self.dataSouce[indexPath.row];
    if ([model.textString containsString:@"地址"] || [model.textString containsString:@"目的地"]) {
        return 88;
    }
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    [cell setSt_tableEasyModel:self.dataSouce[indexPath.row]];
    cell.detailTextLabel.numberOfLines = 0;
    cell.accessoryType = UITableViewCellAccessoryNone;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)onSelectedPhoneButton{
    if (!self.detailModel.phone.length) {
        if (self.detailModel.inventory.integerValue > 0) {
            [self showPayAlert];
        }else{
            [SVProgressHUD showInfoWithStatus:@"该货运商品已售罄"];
        }
        
    }else{
        //打电话
        NSMutableString* str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",self.detailModel.phone];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}
- (void)onSelectedContactButton{
    if (!self.detailModel.phone.length) {
        //付钱
        if (self.detailModel.inventory.integerValue > 0) {
            [self showPayAlert];
        }else{
            [SVProgressHUD showInfoWithStatus:@"该货运商品已售罄"];
        }
    }else{
        //环信
        NSString * phone = self.detailModel.phone ;
        BOOL isSelf =  [[STUserManger defult].phone isEqualToString:phone];
        if (isSelf) {
            [SVProgressHUD showInfoWithStatus:@"这是你自己发布的产品哟"];
            return;
        }
        KLMessageChatViewController * vc = [[KLMessageChatViewController alloc] initWithConversationChatter:phone conversationType:EMConversationTypeChat];
        [self.navigationController pushViewController:vc animated:YES];
    }
}
#pragma mark --Private Method
- (void)showPayAlert{
    NSString * title = [NSString stringWithFormat:@"您将要支付%@元获取电话号码",self.detailModel.money];
    [self showAlertTitle:title message:@"请问继续吗？" leftTitle:@"取消" rightTitle:@"支付" block:^(NSString *name) {
        if ([name isEqualToString:@"支付"]) {
            //支付
            [self showPayStyle];
        }
    }];
}
- (void)showPayStyle{
    STActionSheet  * action = [STActionSheet actionSheetWithTitle:@"支付方式" buttonTitles:@[@"微信",@"支付宝"] cancelTitle:@"取消" delegate:self];
    [action show];
}
#pragma mark --STActionSheetDelegate
- (void)actionSheet:(STActionSheet *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //微信
        [self sendWeChatPayRequest];
    }
    if (buttonIndex == 1) {
        //支付宝
        [self sendAlitPayRequest];
    }
}
#pragma mark --NetWork Method
- (void)sendDetailRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (self.model) {
        [dic setObject:self.model.freight_id forKey:@"freight_id"];
    }
    NSString * url;
    if ([STUserManger defult].token.length) {
       url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/freight/freightinfo",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    }else{
        url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/freight/freightinfo",[NSString stringWithFormat:@"?token="]];
    }
    
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"info"]) {
                                                     self.detailModel = [KLCarDetailModel mj_objectWithKeyValues:dataDic[@"info"]];
                                                     if ([dataDic.allKeys containsObject:@"money"]) {
                                                         self.detailModel.money = dataDic[@"money"];
                                                     }
                                                     [self reloadData];
                                                 }
                                                 [self configSubView];
                                                 
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self.tableView.mj_header endRefreshing];
                                                 
                                             }];
}
- (void)sendWeChatPayRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (self.detailModel) {
        [dic setObject:self.detailModel.freight_id forKey:@"freight_id"];
    }
    [dic setObject:@"wxpay" forKey:@"type"];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/freight/pay",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"pay_data"]) {
                                                     NSDictionary * wechatDic = dataDic[@"pay_data"];
                                                     //wechat
                                                     PayReq *request = [PayReq new];
                                                     request.nonceStr = wechatDic[@"noncestr"];
                                                     request.package = wechatDic[@"package"];
                                                     request.partnerId = wechatDic[@"partnerid"];
                                                     request.prepayId = wechatDic[@"prepayid"];
                                                     request.sign = wechatDic[@"sign"];
                                                     request.timeStamp = [wechatDic[@"timestamp"] intValue];
                                                     [WXApi sendReq:request];
                                                 }
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendAlitPayRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    if (self.detailModel) {
        [dic setObject:self.detailModel.freight_id forKey:@"freight_id"];
    }
    [dic setObject:@"alipay" forKey:@"type"];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/freight/pay",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"pay_data"]) {
                                                     NSString * alipayStr = dataDic[@"pay_data"];
                                                     //alipay
                                                     [[AlipaySDK defaultService] payOrder:alipayStr fromScheme:@"KunLun" callback:^(NSDictionary *resultDic) {
                                                         NSLog(@"reslut = %@",resultDic);
                                                         //回调在appdelegate 中
                                                     }];
                                                 }
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
#pragma mark -图片查看
- (void)onSelectedImageView:(UIGestureRecognizer*)ges{
    UIImageView * imageView = (id)ges.view;
    NSMutableArray * dataSouce = [NSMutableArray new];
    for (NSString * url in self.detailModel.pictures) {
        STUrlPhotoModel * model = [STUrlPhotoModel new];
        model.originImageUrl = url;
        model.thumbImageUrl = url;
        //        model.originImage = imageView.image;
        [dataSouce addObject:model];
    }
    NSInteger tag = imageView.tag - 10000;
    STPhotoUrlImageBrowerController *  vc = [[STPhotoUrlImageBrowerController alloc] initWithArray:dataSouce curentIndex:tag];
    vc.shouldHideBottomView = YES;
    [self presentViewController:vc animated:NO completion:nil];
}
@end

